package com.freewater.javabase.demo.network.post;

import com.google.common.collect.Lists;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class QueryString {

    private List<String> keys;

    private List<String> values;

    public QueryString() {
        keys = Lists.newArrayList();
        values = Lists.newArrayList();
    }

    public QueryString add(String key, String value) {
        if (key == null || key.isBlank()) {
            throw new IllegalArgumentException("key is null or empty");
        }
        keys.add(key);
        values.add(value);
        return this;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            final String key = keys.get(i);
            final String value = values.get(i);
            if (i != 0) {
                builder.append("&");
            }
            builder.append(key.trim() + "=" + (value == null ? "" : URLEncoder.encode(value, StandardCharsets.UTF_8)));
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        QueryString queryString = new QueryString();
        System.out.println(queryString);
        queryString.add("key1", "值1");
        queryString.add("key1", "值1");
        System.out.println(queryString);
    }
}
